package cn.newgrand.netcall.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.spark.PluginManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.RolloverButton;
import org.jivesoftware.spark.component.Table;
import org.jivesoftware.spark.component.TitlePanel;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomNotFoundException;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.log.Log;

import cn.newgrand.netcall.ExpertPlugin;
import cn.newgrand.netcall.resources.ExpertRes;
import cn.newgrand.netcall.util.StringUtil;
import cn.newgrand.smackx.specialist.ExpertManager;
import cn.newgrand.smackx.specialist.entity.Expert;
import cn.newgrand.smackx.specialist.packet.CurrentAskerIQ;
import cn.newgrand.smackx.specialist.packet.NotifyNextAskerIQ;

/**
 * 专家上线注销界面
 * @author UP
 *
 */
public class ExpertConfigUI extends JPanel implements PacketListener{
	
	private static final long serialVersionUID = 1L;
	private final RolloverButton loginButton = new RolloverButton("上线", SparkRes.getImageIcon(SparkRes.SMALL_USER1_NEW));
    private final RolloverButton exitButton = new RolloverButton("注销", SparkRes.getImageIcon(SparkRes.DOOR_IMAGE));
    private final RolloverButton setWelcomeInfoButton = new RolloverButton("设置专家资料", SparkRes.getImageIcon(SparkRes.EXPERT_INFORMATION));
    private final JLabel currentAskerLable = new JLabel("等待咨询");
    private final RolloverButton startButton = new RolloverButton("开始");
    private final RolloverButton nextButton = new RolloverButton("下一位", SparkRes.getImageIcon(SparkRes.SMS_SEND_TO_GROUP));
    private final JLabel leavewordInfoLabel = new JLabel("当前暂无留言.");
    private final RolloverButton lookLeaveWordBtn = new RolloverButton("查看留言",ExpertRes.getImageIcon(ExpertRes.LOOK_LEAVEWORD_IMAGE));
	private RoomList expertTable;
	private String currentAsker = "";
	private String leavewordCount = "";
	
	public ExpertConfigUI(String count){
		this.setLayout(new BorderLayout());
		leavewordCount = count;
		JPanel toolPanel = new JPanel(new BorderLayout());
		JPanel cPanel = new JPanel(new FlowLayout());
		JPanel nPanel = new JPanel(new FlowLayout());
		loginButton.setEnabled(false);
		exitButton.setEnabled(false);
		setWelcomeInfoButton.setEnabled(false);
		nextButton.setEnabled(false);
		cPanel.add(loginButton);
		cPanel.add(exitButton);
		cPanel.add(setWelcomeInfoButton);
//		toolPanel.add(loginButton,BorderLayout.CENTER);
//		toolPanel.add(exitButton,BorderLayout.CENTER);
//		toolPanel.add(setWelcomeInfoButton,BorderLayout.CENTER);
		toolPanel.add(cPanel,BorderLayout.CENTER);
//		toolPanel.add(currentAskerLable,BorderLayout.NORTH);
//		toolPanel.add(nextButton,BorderLayout.NORTH);
		nPanel.add(currentAskerLable);
		nPanel.add(startButton);
		nPanel.add(nextButton);
		toolPanel.add(nPanel,BorderLayout.NORTH);
		this.add(toolPanel,BorderLayout.NORTH);
		expertTable = new RoomList();
        final JScrollPane pane = new JScrollPane(expertTable);
        pane.setBackground(Color.white);
        pane.setForeground(Color.white);
        this.setBackground(Color.white);
        this.setForeground(Color.white);
        pane.getViewport().setBackground(Color.white);
        this.add(pane, BorderLayout.CENTER);
        JPanel bottomPanel = new JPanel(new BorderLayout());
        if("".equals(leavewordCount)){
        	lookLeaveWordBtn.setEnabled(false);
        }else{
        	leavewordInfoLabel.setText("当前您有"+leavewordCount+"条留言.");
        }
        bottomPanel.add(leavewordInfoLabel, BorderLayout.WEST);
        bottomPanel.add(lookLeaveWordBtn, BorderLayout.EAST);
        this.add(bottomPanel, BorderLayout.SOUTH);
        
        loginButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				expertLogin();
			}
		});
        
        exitButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				expertExit();
			}
		});
        
        setWelcomeInfoButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				setWelcomeInfo();
			}
		});
        
        nextButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				notifyNextAsker();
			}
		});
        
        startButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if(currentAsker.length() > 0){
					String bareJid = StringUtil.getBaseJid(currentAsker);
					String nickname = SparkManager.getUserManager().getUserNicknameFromJID(bareJid);
					ChatRoom chatRoom = SparkManager.getChatManager().createChatRoom(bareJid, nickname, nickname);
					SparkManager.getChatManager().getChatContainer().activateChatRoom(chatRoom);
				}else{
					JOptionPane.showMessageDialog(ExpertConfigUI.this, "等待咨询", "消息", JOptionPane.WARNING_MESSAGE);
				}
			}
		});
        
        lookLeaveWordBtn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				//查看留言
				((ExpertPlugin)PluginManager.getInstance().getPlugin(ExpertPlugin.class)).getExpertButton().setText("");
				ExpertManager.getInstance(SparkManager.getConnection()).loadLeaveword();
				leavewordInfoLabel.setText("当前暂无留言.");
				lookLeaveWordBtn.setEnabled(false);
			}
		});
        addTableListener();
        PacketFilter packetFilter = new PacketTypeFilter(IQ.class);
		SparkManager.getConnection().addPacketListener(this, packetFilter);
        //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	private class RoomList extends Table{
		private static final long serialVersionUID = 1L;

		public RoomList(){
			super(new String[]{"","专家号", "擅长", "最大队列数", "本月在线时间"});
			getColumnModel().getColumn(0).setMaxWidth(30);
            getColumnModel().setColumnMargin(0);
            setSelectionBackground(Table.SELECTION_COLOR);
            setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            setRowSelectionAllowed(true);
		}
	}
	
	private void addTableListener(){
		expertTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent e) {
				int selectedRow = expertTable.getSelectedRow();
				//根据专家的上线情况来判断按钮是否可用
				String expertname = (String)expertTable.getValueAt(selectedRow, 1);
				if(-1 != selectedRow){
					setWelcomeInfoButton.setEnabled(true);
					if(ExpertManager.getInstance(SparkManager.getConnection()).isOnline(expertname)){
						loginButton.setEnabled(false);
						exitButton.setEnabled(true);
						nextButton.setEnabled(true);
					}else{
						loginButton.setEnabled(true);
						exitButton.setEnabled(false);
						nextButton.setEnabled(false);
					}
				}
			}
		});
	}
	
	public void invoke(){
		//查询当前在线的专家的正在咨询的咨询者jid
		final Map<String, Expert> onlineExperts = ExpertManager.getInstance(SparkManager.getConnection()).getOnlineExperts();
		if(onlineExperts.size() == 1){
			SwingWorker worker = new SwingWorker() {
				
				@Override
				public Object construct() {
					return null;
				}
				public void finished(){
					String spid = "";
					Set<String> spids = onlineExperts.keySet();
					for (String string : spids) {
						spid = string;
					}
					CurrentAskerIQ askerIQ = ExpertManager.getInstance(SparkManager.getConnection()).getCurrentAsker(spid);
					if(askerIQ != null && askerIQ.getError() == null){
						currentAsker = askerIQ.getAskerJid();
						if(currentAsker.length() > 0){
							currentAskerLable.setText("当前咨询者是："+StringUtil.getJidNode(currentAsker));
						}
					}
				}
			};
			worker.start();
			
		}
		SwingWorker worker = new SwingWorker() {
			Collection<Expert> experts;
			@Override
			public Object construct() {
				experts = ExpertManager.getInstance(SparkManager.getConnection()).getExperts();
				return "OK";
			}
			
			public void finished(){
				if (experts == null) {
                    JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "你不拥有专家身份", Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
                }
				for (Expert expert : experts) {
					String onlineTime = ExpertManager.getInstance(SparkManager.getConnection()).searchOnlineTime(expert.getExpertname());
					addExpertToTable(expert.getExpertname(),expert.getSpecialty(),expert.getMaxuser(),expert.isOnline(),onlineTime);
				}
			}
		};
		worker.start();
		final JDialog dlg;
		final JOptionPane pane;
		TitlePanel titlePanel;

        // Create the title panel for this dialog
        titlePanel = new TitlePanel("提示:您同一时间只能以一种专家的身份上线!", null, null, false);


        // Construct main panel w/ layout.
        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(titlePanel, BorderLayout.NORTH);
        // The user should only be able to close this dialog.
        Object[] options = {Res.getString("close")};
        pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);

        mainPanel.add(pane, BorderLayout.CENTER);

        final JOptionPane p = new JOptionPane();
        
        dlg = p.createDialog(SparkManager.getMainWindow(), "我是专家");
        dlg.setModal(false);
        dlg.pack();
        /* looking up which bundle is used to set the size of the Window 
           (not using Localpreferences getLanguage() because sometimes language is not saved
           in the properties file and so the method only returns an empty String) */
      	dlg.setSize(490, 400);
        
        PropertyChangeListener changeListener = new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
                String value = (String)pane.getValue();
                if (Res.getString("close").equals(value)) {
                    pane.removePropertyChangeListener(this);
                    SparkManager.getConnection().removePacketListener(ExpertConfigUI.this);
                    dlg.dispose();
                }
                else if (Res.getString("close").equals(value)) {
                    pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
                }
            }
        };  
        pane.addPropertyChangeListener(changeListener);
        //dlg.setResizable(true);
        dlg.setContentPane(mainPanel);
        dlg.setLocationRelativeTo(SparkManager.getMainWindow());
        
        dlg.setVisible(true);
        dlg.toFront();
        dlg.requestFocus();
	}
	
	public void expertLogin(){
		if(ExpertManager.getInstance(SparkManager.getConnection()).getOnlineExperts().size() > 0){
			Collection<Expert> onlineExperts = ExpertManager.getInstance(SparkManager.getConnection()).getOnlineExperts().values();
			int expertCount = ExpertManager.getInstance(SparkManager.getConnection()).getExperts().size();
			for(Expert expert : onlineExperts){
				for(int i = 0; i < expertCount; i++){
					String expertname = (String)expertTable.getValueAt(i, 1);
					if(expertname.equals(expert.getExpertname())){
						JLabel flagTable = (JLabel)expertTable.getValueAt(i, 0);
						flagTable.setIcon(SparkRes.getImageIcon(SparkRes.IM_UNAVAILABLE_STALE_IMAGE));
						break;
					}
				}
				ExpertManager.getInstance(SparkManager.getConnection()).expertExit(expert.getExpertname());
				break;
			}
			//如果存在多个身份上线用下面的方法
			//ExpertManager.getInstance().expertExit(ExpertManager.getInstance().getOnlineExperts());
		}
		int selectedRow = expertTable.getSelectedRow();
		if(selectedRow != -1){
			String expertname = (String)expertTable.getValueAt(selectedRow, 1);
			boolean result = ExpertManager.getInstance(SparkManager.getConnection()).expertLogin(expertname);
			if(result){
				JLabel flagTable = (JLabel)expertTable.getValueAt(selectedRow, 0);
				flagTable.setIcon(SparkRes.getImageIcon(SparkRes.GREEN_BALL));
				loginButton.setEnabled(false);
				exitButton.setEnabled(true);
				nextButton.setEnabled(true);
			}
		}
	}
	
	public void expertExit(){
		int selectedRow = expertTable.getSelectedRow();
		if(selectedRow != -1){
			String expertname = (String)expertTable.getValueAt(selectedRow, 1);
			boolean result  = ExpertManager.getInstance(SparkManager.getConnection()).expertExit(expertname);
			if(result){
				JLabel flagTable = (JLabel)expertTable.getValueAt(selectedRow, 0);
				flagTable.setIcon(SparkRes.getImageIcon(SparkRes.IM_UNAVAILABLE_STALE_IMAGE));
				loginButton.setEnabled(true);
				exitButton.setEnabled(false);
				nextButton.setEnabled(false);
			}
		}
	}
	
	public void notifyNextAsker(){
		int selectedRow = expertTable.getSelectedRow();
		if(selectedRow != -1){
			String expertname = (String)expertTable.getValueAt(selectedRow, 1);
			if(currentAsker.length() == 0){
				JOptionPane.showMessageDialog(this, "队列为空,等待咨询者加入队列.", "消息", JOptionPane.PLAIN_MESSAGE);
				return;
			}
			NotifyNextAskerIQ notifyAskerIQ = ExpertManager.getInstance(SparkManager.getConnection()).notifyNextAsker(expertname,currentAsker);
			if(notifyAskerIQ != null && notifyAskerIQ.getError() == null){
				String result = notifyAskerIQ.getResult();
				if("expertoffline".equals(result)){
					JOptionPane.showMessageDialog(this, "该专家身份不存在或不在线", "消息", JOptionPane.PLAIN_MESSAGE);
				}else if("askerempty".equals(result)){
					JOptionPane.showMessageDialog(this, "您的专家队列为空,等待咨询者加入队列.", "消息", JOptionPane.PLAIN_MESSAGE);
				}else if("noasking".equals(result)){
					JOptionPane.showMessageDialog(this, notifyAskerIQ.getAskerJid()+"该咨询者还没开始会话,不能通知下一位", "消息", JOptionPane.PLAIN_MESSAGE);
				}else if("alreadyover".equals(result)){
					String userJid = notifyAskerIQ.getAskerJid();
					JOptionPane.showMessageDialog(this, StringUtil.getJidNode(userJid)+"咨询者自己已经结束了咨询.", "消息", JOptionPane.PLAIN_MESSAGE);
				}else if("nextempty".equals(result)){
					String userJid = notifyAskerIQ.getAskerJid();
					userJid = StringUtil.getBaseJid(userJid);
					try {
						ChatRoom chatRoom = SparkManager.getChatManager().getChatContainer().getChatRoom(userJid);
						SparkManager.getChatManager().getChatContainer().closeChatRoom(chatRoom);
					} catch (ChatRoomNotFoundException e) {
						// ignore
					}
					JOptionPane.showMessageDialog(this, "已结束了"+StringUtil.getJidNode(userJid)+"的咨询,暂无新的咨询者.", "消息", JOptionPane.PLAIN_MESSAGE);
				}else if("success".equals(result)){
					String userJid = notifyAskerIQ.getAskerJid();
					userJid = StringUtil.getBaseJid(userJid);
					try {
						ChatRoom chatRoom = SparkManager.getChatManager().getChatContainer().getChatRoom(userJid);
						SparkManager.getChatManager().getChatContainer().closeChatRoom(chatRoom);
					} catch (ChatRoomNotFoundException e) {
						// ignore
					}
					JOptionPane.showMessageDialog(this, "已结束了"+StringUtil.getJidNode(userJid)+"的咨询,并通知了下一位咨询者,请等待.", "消息", JOptionPane.PLAIN_MESSAGE);
				}else{
					Log.error("专家通知下一位咨询者异常.");
				}
			}
		}
	}
	
	public void setWelcomeInfo(){
		int selectedRow = expertTable.getSelectedRow();
		if(selectedRow != -1){
			String expertname = (String)expertTable.getValueAt(selectedRow, 1);
//			new ExpertBaseInfoUI(expertname);
			new ExpertInfoConfig(expertname);
		}
	}
	
	public void addExpertToTable(String expertname,String specialty,String maxuser,boolean b,String onlineTime){
		JLabel flagTable = new JLabel();
		if(b){
			flagTable.setIcon(SparkRes.getImageIcon(SparkRes.GREEN_BALL));
		}else{
			flagTable.setIcon(SparkRes.getImageIcon(SparkRes.IM_UNAVAILABLE_STALE_IMAGE));
		}
		Object[] expertObj = new Object[]{flagTable,expertname,specialty,maxuser,onlineTime};
		expertTable.getTableModel().addRow(expertObj);
	}

	@Override
	public void processPacket(Packet packet) {
		if(packet instanceof CurrentAskerIQ){
			CurrentAskerIQ nextAsker = (CurrentAskerIQ)packet;
			currentAsker = nextAsker.getAskerJid();
			if(currentAsker.length() > 0){
				currentAskerLable.setText("当前咨询者是："+StringUtil.getJidNode(currentAsker));
			}else{
				currentAskerLable.setText("等待咨询");
			}
		}
	}
	
}
